﻿Imports TyranntEngine

Public Class DungeonDatabaseAccess

    Private _LastError As New Exception
    Private _causedError As Boolean = False
    Private db As New TyranntDungeonDatasourceDataContext

#Region "Maze Object"

    Public Function NewMazeObject(ByVal objectXML As String) As String
        ' Create a new object and process the XML
        Dim mObj As New dungeonObject
        Try
            mObj.LoadXML(objectXML)
        Catch ex As Exception
            Return FailedXML("NewMazeObject", objectXML)
        End Try

        ' Check to see if the object already exists in the database
        Dim dbObject As mazeObject = PullMazeObject(mObj.Name)
        ' if the returned object is null then something failed
        If IsNothing(dbObject) = True Then
            Return Failed("PullMazeObject")
        End If
        ' If the returned object name is set to something then the object
        ' already exists.
        If dbObject.name <> "" Then
            Return ErrorRoutine(-5, "MazeObject", "NewMazeObject")
        End If
        ' So we have a new maze object, lets populate it
        dbObject.name = mObj.Name
        dbObject.description = mObj.Description
        dbObject.type = mObj.ObjectType
        dbObject.model = mObj.ModelName
        dbObject.texture = mObj.TextureName

        ' Now try to add to the database
        Try
            db.mazeObjects.InsertOnSubmit(dbObject)
            db.SubmitChanges()
        Catch ex As Exception
            _LastError = ex
            Return Failed("NewMazeObject")
        End Try
        ' Success so return ""
        Return ""
    End Function

    Public Function UpdateMazeObject(ByVal objectXML As String) As String
        ' Create a new object and process the XML
        Dim mObj As New dungeonObject
        Try
            mObj.LoadXML(objectXML)
        Catch ex As Exception
            Return FailedXML("NewMazeObject", objectXML)
        End Try

        ' Check to see if the object exists in the database
        Dim dbObject As mazeObject = PullMazeObject(mObj.Name)
        ' if the returned object is null then something failed
        If IsNothing(dbObject) = True Then
            Return Failed("PullMazeObject")
        End If
        ' If the returned object name is "" then object not exist
        If dbObject.name = "" Then
            Return ErrorRoutine(-1, "MazeObject", "UpdateMazeObject")
        End If
        ' So we have the maze object, lets update it
        dbObject.name = mObj.Name
        dbObject.description = mObj.Description
        dbObject.type = mObj.ObjectType
        dbObject.model = mObj.ModelName
        dbObject.texture = mObj.TextureName

        ' Now try to update to the database
        Try
            db.SubmitChanges()
        Catch ex As Exception
            _LastError = ex
            Return Failed("UpdateMazeObject")
        End Try

        ' Success so return ""
        Return ""
    End Function

    Public Function DeleteMazeObject(ByVal name As String) As String
        ' Lets try to pull the object from the database
        Dim dbObject As mazeObject = PullMazeObject(name)
        ' if the returned object is null then something failed
        If IsNothing(dbObject) = True Then
            Return Failed("PullMazeObject")
        End If
        ' If the returned object name is "" then object not exist
        If dbObject.name = "" Then
            Return ErrorRoutine(-1, "MazeObject", "DeleteMazeObject")
        End If
        ' So we have the maze object, lets delete it
        Try
            db.mazeObjects.DeleteOnSubmit(dbObject)
            db.SubmitChanges()
        Catch ex As Exception
            _LastError = ex
            Return Failed("DeleteMazeObject")
        End Try

        ' Success so return ""
        Return ""
    End Function

    Public Function GetMazeObject(ByVal name As String) As String
        ' Lets try to pull the object from the database
        Dim dbObject As mazeObject = PullMazeObject(name)
        ' if the returned object is null then something failed
        If IsNothing(dbObject) = True Then
            Return Failed("PullMazeObject")
        End If
        ' If the returned object name is "" then object not exist
        If dbObject.name = "" Then
            Return ErrorRoutine(-1, "MazeObject", "GetMazeObject")
        End If
        ' So we have the maze object, lets turn it into a dungeon object
        ' so we can generate the XML to return.
        Dim mObj As New dungeonObject
        mObj.ID = dbObject.ID
        mObj.Name = dbObject.name
        mObj.Description = dbObject.description
        mObj.ObjectType = dbObject.type
        mObj.ModelName = dbObject.model
        mObj.TextureName = dbObject.texture
        Return mObj.ToXElement.ToString
    End Function

    Public Function GetMazeObjects() As String
        ' lets query the database and pull all the maze objects into
        ' an XML document (Got to love VB :) )
        Try
            Dim result As XElement = <mazeObjects>
                                         <%= From mObj In db.mazeObjects _
                                             Select <mazeObject id=<%= mObj.ID %>>
                                                        <name><%= mObj.name %></name>
                                                        <type><%= mObj.type %></type>
                                                    </mazeObject> %>
                                     </mazeObjects>
            Return result.ToString
        Catch ex As Exception
            _LastError = ex
            Return Failed("GetMazeObjects")
        End Try
    End Function

    Private Function PullMazeObject(ByVal name As String) As mazeObject
        Try
            Dim result = (From mObj In db.mazeObjects _
                          Where mObj.name = name _
                          Select mObj).ToList
            If result.Count = 0 Then
                Return New mazeObject
            Else
                Return result(0)
            End If
        Catch ex As Exception
            _LastError = ex
            Return Nothing
        End Try
    End Function

#End Region

#Region "General Code"

    Public Function ErrorRoutine(ByVal errCode As Integer, ByVal context As String, ByVal routine As String) As String
        Select Case errCode
            Case -1
                Return "[#]" + context + "notexist[" + routine + "]"
            Case -2
                Return Failed(routine)
            Case -3
                Return "[#]" + context + "permissiondenied[" + routine + "]"
            Case -4
                Return "[#]" + context + "[" + routine + "]"
            Case -5
                Return "[#]" + context + "alreadyexist[" + routine + "]"
            Case Else
                Return "[#]" + context + "unknowncode[" + routine + "]"
        End Select
    End Function

    Public Function Failed(ByVal routine As String) As String
        Return "[#]failed[" + routine + "]|" + _LastError.ToString
    End Function

    Public Function FailedXML(ByVal routine As String, ByVal xmlData As String) As String
        Return "[#]failed[" + routine + "]|" + _LastError.ToString + vbCrLf + vbCrLf + xmlData
    End Function

    Public ReadOnly Property LastError() As Exception
        Get
            Return _LastError
        End Get
    End Property

#End Region

End Class
